<template>
	<view class="container">

		<view class="">
			<u-subsection fontSize="14px" :list="list" :current="curNow" @change="sectionChange" bgColor="#3c9cff">
			</u-subsection>
		</view>

		<view>
			<u--form labelPosition="left" :model="device" :rules="rules" ref="uForm">
				<u-form-item label="商户名称" prop="searchName" labelWidth="70px">
					<u--input v-model="device.searchName" border="none" placeholder="请输入酒店关键字" trim
						@blur="inputChange(event)"></u--input>
				</u-form-item>


				<u-form-item prop="merchantId" required labelWidth="70px">
					<view class="uni-px-5 uni-pb-5">
						<uni-data-select v-model="device.merchantId" :localdata="merchantNameList"
							placeholder="请选择酒店"></uni-data-select>
					</view>
				</u-form-item>

<!-- 				<u-form-item required label="套餐类型" prop="setMealId" labelWidth="70px">
					<view class="uni-px-5 uni-pb-5">
						<uni-data-select v-model="device.setMealId" :localdata="setMealList"
							@change="inputSelectChange"></uni-data-select>
					</view>
				</u-form-item>

				<u-form-item required label="详情:" prop="setMealInfo" labelWidth="70px">
					<u--textarea v-model="device.setMealInfo" border="bottom" disabled></u--textarea>
				</u-form-item> -->

				<u-form-item required label="设备编码:" prop="deviceNumberBegin" labelWidth="80px" />
				<view class="myMeal1">
					<view class="" style="width:47%;">
						<u-form-item prop="startTotalPay">
							<u--input v-model="device.deviceNumberBegin" border="none" maxlength="15" trim
								placeholder="cj241121"></u--input>
						</u-form-item>

					</view>
					<view class="" style="width:53%;">
						<u-form-item label="-" prop="startTotalPay" labelWidth="20px">
							<u--input v-model="device.deviceNumberEnd" border="none" maxlength="15" trim
								placeholder="cj241141"></u--input>
						</u-form-item>
					</view>
				</view>
				<u-button type="primary" @click="submit">提交</u-button>
				<view>

					<button type="primary" @click="takePhoto"
						style="margin-top: 20px; height: 38px; font-size: 14px;">扫码上传</button>


				</view>
			</u--form>
		</view>
	</view>

	</view>
</template>

<script>
	import {
		listBinding,
		getBinding,
		addBinding,
		updateBinding,
		delBinding
	} from "@/api/system/device";

	import {
		getList,
	} from "@/api/system/user";

	import {
		listMeal
	} from '@/api/system/setmeal'

	export default {

		data() {
			return {
				src: "",
				list: ['上传设备', '修改类型', '查找设备'],
				curNow: 0,
				merchantNameList: [],
				setMealList: [],
				setMealInfoLists: [],
				device: {
					searchName: '',
					merchantId: '',
					setMealId: '',
					deviceNumberBegin: '',
					deviceNumberEnd: '',
					setMealInfo: '',
					pageNum: 1,
					pageSize: 50,
					code: ''
				},

				rules: {
					'merchantId': [{
						type: 'any',
						required: true,
						message: '那个场所',
						max: 8,
						trigger: ['blur', 'change']
					}],

					'setMealId': [{
						type: 'any',
						required: true,
						message: 'select',
						max: 8,
						trigger: ['blur', 'change']
					}],
					'deviceNumberBegin': [{
						type: 'string',
						required: true,
						message: '填入开始编码',
						trigger: ['blur', 'change']
					}],

					'deviceNumberEnd': [{
						type: 'string',
						required: true,
						message: '填入结束编码',
						trigger: ['blur', 'change']
					}],



				},
			};
		},
		async onReady() {
			const res = await listMeal(this.device);
			console.log(JSON.stringify(res.rows));
			this.setMealList = [];
			this.setMealInfoLists = [];
			// 遍历返回的每一行数据
			this.setMealInfoLists = res.rows.map(item => {
				const newObj = {};
				// 遍历每个对象的键值对
				for (const [key, value] of Object.entries(item)) {
					newObj[key] = value; // 将键值对添加到 newObj 中
				}
				return newObj; // 返回转换后的对象
			});

			res.rows.forEach((val, index) => {
				this.setMealList.push({
					value: val.id,
					text: val.name,
				})
			})
		},
		methods: {
			async takePhoto() {
				console.log('1' + this.device.merchantId)
				if (this.device.merchantId == "") {
					uni.$u.toast('酒店名称必选')
					return
				}

		
				const code = await new Promise((resolve, reject) => {
					wx.scanCode({
						success: (res) => {
							console.log(JSON.stringify(res))
							if (res.result.indexOf("?s=") > 0) {
								const code = res.result.split("?s=");
								console.log('箭头函数' + JSON.stringify(this.device))
								resolve(code[1])
							} else {
								reject('扫描的二维码不包含有效信息');
							}
						}
					})
				})

				console.log("code:", code)
				this.device.code = '';
				this.device.code = code;
				console.log(JSON.stringify(this.device))
				await addBinding(this.device).then(res => {
					uni.$u.toast(res.msg);
				}).catch(error => {
					console.log('调用后端添加套餐失败' + JSON.stringify(error))
				})




			},
			error(e) {
				console.log(e.detail);
			},
			async inputChange(e) {
				this.device.merchantId = '';
				console.log(3)
				console.log(this.device.searchName)
				if (this.device.searchName == '') {
					this.merchantNameList = [];
					return
				}
				let requstData = {
					merchantName: ''
				}
				requstData.merchantName = this.device.searchName;
				const res = await getList(requstData);
				console.log(JSON.stringify(res.data));
				this.merchantNameList = [];
				res.data.forEach((val, index) => {
					this.merchantNameList.push({
						value: val.userId,
						text: val.merchantName
					})
				})
			},
			inputSelectChange(e) {
				// console.log('当前id:' + e);
				const meal = this.setMealInfoLists.find(item => item.id === e);
				this.device.setMealInfo = '前' + meal.startTime + '小时内' + meal.startTotalPay + '元,超出部分 ' + meal
					.incrementPay +
					'/小时; 消费封顶价' + meal.dayTopPay + '元,预付金额' + meal.totalPay + '元';
			},
			sectionChange(index) {
				if (index == this.curNow) {
					return
				}
				let oldCurNow = this.curNow;
				this.curNow = index;
				if (index === 0) {
					uni.navigateTo({
						url: '/pages/device/device'
					})
				} else if (index === 1) {
					uni.navigateTo({
						url: '/pages/device/deviceUpdate'
					})
				} else if (index === 2) {
					uni.navigateTo({
						url: '/pages/device/deviceSearch'
					})
				}
			},
			submit() {

				console.log('1' + this.device.merchantId)
				if (this.device.merchantId == "") {
					uni.$u.toast('酒店名称必选')
					return
				}

				// if (this.device.setMealId == "") {
				// 	uni.$u.toast('套餐必须')
				// 	return
				// }

				if (this.device.deviceNumberBegin.length > this.device.deviceNumberEnd.length) {
					uni.$u.toast('设备编码开始长度不能大于结束长度')
					return
				}
				this.device.code = '';
				console.log(JSON.stringify(this.device))
				this.$refs.uForm.validate().then(res => {
					addBinding(this.device).then(res => {
						uni.$u.toast(res.msg);
					}).catch(error => {
						console.log('调用后端添加套餐失败' + JSON.stringify(error))
					})

				}).catch(errors => {
					uni.$u.toast('校验失败 : ' + JSON.stringify(errors))
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		//width: 94%;
		padding: 12px;
		display: flex;
		flex-direction: column;
		margin: auto;
		background: linear-gradient(180deg, #f0f0f0 0%, #d0eaff 100%);
		height: 100vh;
	}

	.myMeal1 {
		display: flex;
		justify-content: center;
	}
</style>